<?php
/**
 * Author: ngreduce
 * Date: 05.03.11
 * Time: 12:39
 */

class JobController extends Controller
{
    public $layout = '//layouts/column2';
    private $_model;

    /**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}
    
    /**
     * Access rules for controller.
     * @return array
     */
    public function accessRules()
	{
		return array(
			array('allow',
				'actions'=>array('admin','delete','update', 'approve'),
				'users'=>UserModule::getAdmins(),
			),
            array('allow',
                'actions'=>array('index', 'view', 'create', 'suggestTags'),
                'users'=>array('*')
            ),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

    public function init()
    {
        parent::init();
        $this->menu = array(
            array('label'=>Yii::t('mj-base', 'Jobs'), 'url'=>$this->createUrl('job/index')),
            array('label'=>Yii::t('mj-base', 'Create Job'), 'url'=>$this->createUrl('job/create')),
            array('label'=>Yii::t('mj-base', 'Moderation'), 'url'=>$this->createUrl('job/admin'), 'visible'=>UserModule::isAdmin()),
        );
}

    public function actionIndex()
    {
        $criteria=new CDbCriteria(array(
			'condition'=>'status='.Job::STATUS_APPROVED,
			'order'=>'update_time DESC',
			'with'=>'requestCount',
		));
		if(isset($_GET['tags'])) {
            $tags = explode(' ', $_GET['tags']);
            foreach ($tags as $tag) {
			    $criteria->addSearchCondition('tags',$tag);
            }
        }

		$dataProvider=new CActiveDataProvider('Job', array(
			'pagination'=>array(
				'pageSize'=>Yii::app()->params['itemsPerPage'],
			),
			'criteria'=>$criteria,
		));

		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
    }

    public function actionView()
    {
        $job=$this->loadModel();
        if (isset($_REQUEST['ajax'])) {
            $this->beginWidget('CMarkdown', array('purifyOutput'=>true));
			echo CHtml::encode($job->content);
			$this->endWidget();

            Yii::app()->end();
        }

		$request=$this->newRequest($job);

		$this->render('view',array(
			'model'=>$job,
			'request'=>$request,
		));
    }

    public function actionCreate()
    {
        $model = new Job;
		if(isset($_POST['ajax']) && $_POST['ajax']==='job-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
		if(isset($_POST['Job']))
		{
			$model->attributes=$_POST['Job'];
			if($model->validate()) {
                if ($model->save()) {
                    MailNotificationHelper::adminPengingItem($model);
                    Yii::app()->user->setFlash('job-create','Job successifuly created.');
				    $this->refresh();
                }
			}
		}
		$this->render('create', array('model'=>$model));
    }

    // admin actions

    public function actionAdmin()
    {
        $criteria=new CDbCriteria(array(
			'condition'=>'status='.Job::STATUS_PENDING,
			'order'=>'update_time DESC',
		));

		$dataProvider=new CActiveDataProvider('Job', array(
			'pagination'=>array(
				'pageSize'=>Yii::app()->params['itemsPerPage'],
			),
			'criteria'=>$criteria,
		));

		$this->render('admin',array(
			'dataProvider'=>$dataProvider,
		));
    }

    public function actionUpdate()
    {
        $this->render('update');
    }

    public function actionApprove()
    {
        if (Job::model()->updateByPk($_POST['id'], array('status'=>Job::STATUS_APPROVED)) != 1)
            throw new CHttpException(500);
    }

    public function actionDelete()
    {
        $model = new ModerationDecline;

        if (isset($_POST['ModerationDecline'])) {
            $model->attributes = $_POST['ModerationDecline'];
            if ($model->validate()) {
                $job = Job::model()->findByPk($model->id);
                if ($job == null) throw new CHttpException(404);
                if (isset($model->reason) and $job->author != null) {
                    MailNotificationHelper::userItemRejected($job->author->email,
                                                     array('reason'=>$model->reason, 'model'=>$job));
                }
                Job::model()->deleteByPk($model->id);
            }
        } else {
            throw new CHttpException(400);
        }

    }

    /**
	 * Suggests tags based on the current user input.
	 * This is called via AJAX when the user is entering the tags input.
	 */
	public function actionSuggestTags()
	{
		if(isset($_GET['q']) && ($keyword=trim($_GET['q']))!=='')
		{
			$tags=JTag::model()->suggestTags($keyword);
			if($tags!==array())
				echo implode("\n",$tags);
		}
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 */
	public function loadModel()
	{
		if($this->_model===null)
		{
			if(isset($_GET['id']))
			{
				if(!UserModule::isAdmin())
					$condition='status='.Job::STATUS_APPROVED;
				else
					$condition='';
				$this->_model=Job::model()->findByPk($_GET['id'], $condition);
			}
			if($this->_model===null)
				throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}

	protected function newRequest($job)
	{
		$request=new JobRequest;
		if(isset($_POST['ajax']) && $_POST['ajax']==='request-form')
		{
			echo CActiveForm::validate($request);
			Yii::app()->end();
		}
		if(isset($_POST['JobRequest']))
		{
			$request->attributes=$_POST['JobRequest'];
			if($job->addRequest($request))
			{
                if ($job->author != null)
                    MailNotificationHelper::userNewJobRequest($job->author->email, array('job'=>$job, 'request'=>$request));
                //Yii::app()->user->setFlash('requestSubmitted','Thank you for your comment. Your comment will be posted once it is approved.');
				$this->refresh();
			}
		}
		return $request;
	}
}
 
